package com.ky.server.main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.ky.server.util.ConfigConstants;
import com.ky.server.util.PropertiesUtil;

public class ServerApp {

	static {
		String xmlPath=PropertiesUtil.getProperty(ConfigConstants.SERVER_FILES_PATH_KEY);
		String resourcesPath=ConfigConstants.SERVER_RESOURCES_PATH;
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(new FileReader(xmlPath));
			Element rootElement = document.getRootElement();
			List<Element> fileElements = rootElement.elements();
			if(fileElements.size()==0) {
				File parentFile = new File(resourcesPath);
				//获取资源文件下的所有文件
				File[] files = parentFile.listFiles();
				//循环遍历文件数组
				for(int i=0;i<files.length;i++) {
					Element fileElement = rootElement.addElement("file");
					fileElement.addAttribute("id", (i+1)+"");
					fileElement.addElement("name").setText(files[i].getName());
					fileElement.addElement("size").setText(String .format("%.2f", files[i].length()/1024.0));
					fileElement.addElement("path").setText(resourcesPath+"/"+files[i].getName());
				}
				OutputFormat format = OutputFormat.createPrettyPrint();
				format.setEncoding("UTF-8");
				XMLWriter writer = new XMLWriter(new FileWriter(xmlPath), format);
				writer.write(document);
				writer.close();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PropertiesUtil.getProperty(ConfigConstants.SERVER_PORT_KEY)));
			System.out.println("服务器端已启动。。。。。。");
			//循环接收客户端的请求
			while(true) {
				Socket clientSocket = serverSocket.accept();
				new Thread(new ServerTaskRunnable(clientSocket)).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}

}
